<?php

namespace app\models;

use yii;
use app\components\BaseActiveRecord;

/**
 * This is the model class for table "{{%banner}}".
 *
 * @property integer $id
 * @property integer $type
 * @property string $title
 * @property string $image
 * @property string $url
 * @property integer $sort
 * @property integer $status
 * @property integer $ctime
 */
class Banner extends BaseActiveRecord {

    const TYPE_POST = 6;

    public static $statusLabels = [
        self::STATUS_NO => '隐藏',
        self::STATUS_YES => '显示',
    ];

    public function init() {
        parent::init();
        $this->sort = 0;
        $this->status = static::STATUS_YES;


    }

    public $cacheId = 'banner_%s';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%banner}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['title', 'image', 'type'], 'required'],
            [['type', 'sort', 'status', 'ctime'], 'integer'],
            [['title', 'image'], 'string', 'max' => 120],
            [['url'], 'string', 'max' => 150]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'type' => '类型',
            'title' => '名称',
            'image' => '广告图',
            'url' => '链接',
            'sort' => '排序',
            'status' => '显示',
            'ctime' => 'Ctime',
        ];
    }

    public static function getTypeLabels(){
        $typeLabels = Activity::$cidLabels;
        $typeLabels[static::TYPE_POST] = '探索未知';
        return $typeLabels;
    }

    public function getBanners($type) {
        return $this->cache($this->cacheId, function () use ($type) {
            return static::find()
                ->where(['status' => static::STATUS_YES, 'type' => $type])
                ->orderBy('sort asc, id desc')
                ->asArray()
                ->all();
        }, $type);
    }

    public function afterSave($insert, $changedAttributes) {
        Yii::$app->cache->delete("banner_{$this->type}");
        parent::afterSave($insert, $changedAttributes);
    }

    public function afterDelete() {
        Yii::$app->cache->delete("banner_{$this->type}");

        parent::afterDelete();
    }

    public static function getBannerByType($type) {
        return static::find()
            ->where(['status' => static::STATUS_YES, 'type' => $type])
            ->asArray()
            ->all();
    }
}
